<template>
  <div class="order" >
    <div class="header">
        <a href="javascript:history.go(-1)"><img src="../assets/images/retreat.png" alt=""/></a>
        <span>{{this.salesOutletName}}</span>
    </div>
    <div id="consumption" class="consumption">
        <div class="">
            <span>消费总额:</span>
            <input type="number" placeholder="询问商家后输入" v-model="amount" @keyup="count" />
        </div>
        <div class="">
            <span>不参加优惠金额:</span>
            <!-- <input type="number" placeholder="询问商家后输入" v-model="noDiscountPrice" @keyup="count" @change="format"/> -->
            <input type="number" placeholder="询问商家后输入" v-model="noDiscountPrice" @keyup="count" @change="format"/>
        </div>
    </div>

    <div id="discount" class="discount">
        
        <div class="" v-show="getPolicy()">
            <p>-{{discount}}</p>
            <span>{{policyMsg}}</span>
        </div>

        <div class="voucher" v-show="voucher.status">
            <p v-if="voucherUse>0">-{{voucher.deductionValue}}</p>
            <p v-if="voucherUse==0">-0</p>
            <span>推荐代金券(满{{voucher.paymentAmountThreshold}}-{{voucher.deductionValue}})</span>
        </div>

        <div class="">
            <p v-if="voucherUse==0">{{[amount,discount] | subAmount}}</p>
            <p v-if="voucherUse>0">{{[amount,voucher.deductionValue,discount] | payAmount}}</p>
            <span>实付金额:</span>
        </div>
    </div>
    <!-- <div class="pay-list-title">支付方式：</div>
    <div class="pay-list">
        <div>
            <input type="radio" v-model="payType" value="alipay" id="alipay"/><label for="alipay">支付宝</label>
        </div>
        <div>
            <input type="radio" v-model="payType" value="ght" id="ght"/><label for="ght">高汇通</label>
        </div>
    </div> -->
    <button id="payment" @click="order" :class="[amount>0 ? '':'disabled']">去支付</button>
    <loading v-show="showLoading"></loading>
    <msg-box ref="msgBox"></msg-box>
    <div class="modal" v-if="mdShow">
        <div class="messageBox">
            <div class="success">
                <p></p>
            </div>
            <p class="amount" v-if='isChance === false'>恭喜您获得{{vouchersAmount}} {{$t('message.yuan')}}代金券</p>
            <div class="message" v-if='isChance'>
                <p>您将有机会获得一张代金券</p>
                <p>请下载壹键哥APP查看</p>
            </div>
            <div class="message" v-else>
                <p>代金券已放入钱包，下次买单可用</p>
                <p>试用期有限，请尽快使用</p>
            </div>
            <div class="close" @click="mdShow=false">知道了</div>
        </div>
    </div>
    <div class="mask" v-if="mdShow" @click="mdShow=false"></div>
    <div v-html="payUrl" id="payUrl"></div>
    <open-app ref="openApp"></open-app>
  </div>
</template>

<script>
import Vue from 'vue'
import loading from './Loading'
import msgBox from './MsgBox';
import openApp from "./OpenApp";
import 'vue-layer-mobile/need/layer.css'
import layer from 'vue-layer-mobile'
import { setTimeout } from 'timers';
import decimal from '../tools/decimal.js'

Vue.use(layer)
export default {
    name: 'order',
    components: {
        loading,
        msgBox,
        openApp
    },
    data() {
        return {
            amount: null,
            noDiscountPrice: null,
            payNoDiscountPrice: 0,
            totalPrice: 0,
            remark: "快捷支付",
            salesOutletName: this.$route.query.salesOutletName,
            policyStatus: false,
            policyMsg: "",
            discount: 0,
            policyInfo: {},
            showLoading: false,
            mdShow: false,
            voucherValue: 0,
            vouchersAmount: 0,
            voucher: {}, //可用的优惠券，一个,
            voucherUse: 0, //优惠券使用金额
            merchantType: 1,
            payUrl: '',
            isChance: false,
            promotion: [], //满减优惠
            lock: 0, // 锁定则不提交
            isShow: false,
            fromPath: ''
        }
    },
    mounted() {
        //this.isAllowPromotionVoucher()
        // this.fromPath = this.$route.query.formPath;
        this.getVoucher();
    },
    beforeRouteEnter(to, from, next) {
        next(vm => {
            if (from.name === 'Register') vm.fromPath = 'Register'
        })
    },
    watch: {
        amount(val) {
            if (isNaN(parseFloat(val))) {
                this.amount = null
            } else {
                if (parseFloat(this.noDiscountPrice) >= val) {
                    this.noDiscountPrice = null
                }
                if (val.length > 16) {
                    this.amount = this.amount.slice(0, 16)
                }
                //截取小数点
                if (String(val).indexOf('.') !== -1) {
                    let len = String(val).split('.')[1]
                    if (len.length > 2) {
                        this.amount = this.MathFloor(Number(val))
                    }
                }
            }
        },
        noDiscountPrice(val) {
            if (isNaN(parseFloat(val))) {
                this.noDiscountPrice = null
            } else {
                if (Number(val) > this.amount) this.noDiscountPrice = null
                if (val.length > 16) {
                    this.noDiscountPrice = this.noDiscountPrice.slice(0, 16)
                }
                //截取小数点
                if (String(val).indexOf('.') !== -1) {
                    let len = String(val).split('.')[1]
                    if (len.length > 2) {
                        this.noDiscountPrice = this.MathFloor(Number(val))
                    }
                }
            }
        },
        payNoDiscountPrice(val) {
            this.payNoDiscountPrice = val
        }
    },
    filters: {
        subAmount([a, b]) {
            if (!isNaN(parseFloat(a)) && !isNaN(parseFloat(b))) {
                return decimal.sub(a, b)
            }
        },
        payAmount([a, b, c]) {
            if (!isNaN(parseFloat(a)) && !isNaN(parseFloat(b)) && !isNaN(parseFloat(c))) {
                let decimalNum = decimal.sub(decimal.sub(a, b), c)
                if (decimalNum < 0) {
                    decimalNum = 0
                }
                return decimalNum
            }
        }
    },
    methods: {
        alert(msg) {
            this.$refs.msgBox.alert(msg);
        },
        order() {
            if (this.amount <= 0) return false
            const orderInfo = {}
            /* amount 实付金额 = 不参加优惠金额 +（TotalPrice-NoDiscountPrice）*优惠政策
               totalPrice 实际消费金额，保留两位小数点
             */
            // if(this.noDiscountPrice <= 0  || this.noDiscountPrice > this.amount){
            //     this.noDiscountPrice = 0
            // }
            if (this.payNoDiscountPrice <= 0 || this.payNoDiscountPrice > this.amount) {
                this.payNoDiscountPrice = 0
            }
            orderInfo.totalPrice = this.amount
            orderInfo.noDiscountPrice = this.payNoDiscountPrice
            orderInfo.amount = decimal.sub(decimal.sub(this.amount, this.voucherUse), this.discount)
            if (orderInfo.amount <= 0) {
                this.alert('订单支付金额不得为0');
                return false
            }
            orderInfo.remark = this.remark;
            if (this.voucherUse > 0) {
                orderInfo.voucherUID = this.voucher.voucherUID;
                orderInfo.voucherType = this.voucher.voucherType;
                orderInfo.voucherAmount = this.voucher.deductionValue;
            }
            this.showLoading = true;
            /* this.$http.post('/api/order',orderInfo).then(res=>{
                if(res.body.payUrl == ""){
                    this.showLoading = false;
                    this.alert('下单失败，请重试. ' + res.body.msg);
                }else{
                    this.showLoading = false;
                    console.log('下单成功');
                    document.location.href = res.body.payUrl;
                }
                console.log(res.body);
            },res=>{
                this.showLoading = false;
                this.alert('请求异常，请稍后重试下单');
            }) */
            this.$http.post('/api/order', orderInfo).then(res => {
                if (res.body.status == 0) {
                    this.showLoading = false;
                    this.alert('下单失败，请重试. ' + res.body.msg);
                } else {
                    this.showLoading = false;
                    /* console.log('下单成功');
                    this.payPlat() */
                    this.$router.push({ 'name': 'Payment', query: { 'amount': orderInfo.amount, 'salesOutletName': this.salesOutletName } });

                }
            }, res => {
                this.showLoading = false;
                this.alert('请求异常，请稍后重试下单');
            })
        },
        //获取店铺优惠方式
        getPolicy() {
            if (this.policyStatus) return true;
            this.$http.post('/api/policy', { salesOutletUID: this.$route.query.salesOutletUID }).then(res => {
                const symbol = res.body.currencySymbol
                this.$i18n.locale = symbol && symbol.toLowerCase().indexOf('hk') >= 0 ? 'zh-hk' : 'zh-cn'
                if (res.body.error == "") {
                    // this.promotion = res.body.promotion.lessContent;
                    const data = res.body.data[0];
                    if (data.supportQuickPay == false) {
                        this.alert('该商家不支持快捷支付');
                        return false;
                    }
                    //优惠类型 1：无优惠；2：按比率优惠；3：满多少减多少（有上限）；4：满多少减多少（无上限）
                    switch (data.discountType) {
                        case 1:
                            this.policyMsg = '无优惠';
                            break;
                        case 2:
                            this.policyMsg = `全单折扣${data.discountRatio}%`;
                            this.policyInfo.discountRatio = data.discountRatio / 100;
                            this.policyInfo.type = 2;
                            break;
                        case 3:
                            this.policyMsg = `满${data.minSalesOrderAmountOfDiscount}减${data.discountAmount}(最高${data.maxDiscountAmount})`;
                            this.policyInfo.minSalesOrderAmountOfDiscount = data.minSalesOrderAmountOfDiscount;
                            this.policyInfo.discountAmount = data.discountAmount;
                            this.policyInfo.maxDiscountAmount = data.maxDiscountAmount;
                            this.policyInfo.type = 3;
                            break;
                        case 4:
                            this.policyMsg = `满${data.minSalesOrderAmountOfDiscount}减${data.discountAmount}(无上限)`;
                            this.policyInfo.minSalesOrderAmountOfDiscount = data.minSalesOrderAmountOfDiscount;
                            this.policyInfo.discountAmount = data.discountAmount;
                            this.policyInfo.type = 4;
                            break;
                    }

                } else {
                    this.policyMsg = res.body.error;
                    this.policyInfo.type = 1;
                }
            }, res => {
                this.alert('请求异常');
            })
            this.policyStatus = true;
            return true;
        },
        formatPrice(value) {
            value = Number(value).toFixed(2)
            if (value === 0) {
                return 0.00
            } else if (value.split('.')[1].substring(1) === 0) {
                value = Number(value).toFixed(1)
            }
            let _val = value.split('.')
            return _val[0] + '.' + _val[1]
        },
        format() {
            this.amount = parseFloat(this.formatPrice(this.amount))
            this.noDiscountPrice = parseFloat(this.formatPrice(this.noDiscountPrice))
        },
        MathFloor(val) {
            let numberFloat = decimal.mul(val, 100)
            return decimal.div(Math.floor(numberFloat), 100)
        },
        count() {
            //先算满减，后算代金券
            let amount = this.amount;
            this.voucherUse = 0;
            if (this.noDiscountPrice < 0) {
                this.noDiscountPrice = null;
                this.payNoDiscountPrice = 0
            }
            switch (this.policyInfo.type) {
                case 2:
                    this.discountPriceRatio = (this.noDiscountPrice === null || decimal.sub(this.noDiscountPrice, this.amount) > 0) ? 0 : this.noDiscountPrice
                    let tempAmount = decimal.mul(decimal.sub(amount, this.discountPriceRatio), decimal.sub(1, this.policyInfo.discountRatio))
                    this.discount = this.MathFloor(tempAmount).toFixed(2);
                    break;
                case 3:
                    let pre_payment = decimal.sub(amount, this.noDiscountPrice);
                    let times = parseInt(decimal.div(pre_payment, this.policyInfo.minSalesOrderAmountOfDiscount));
                    this.discount = decimal.mul(this.policyInfo.discountAmount, times);
                    if (this.discount > this.policyInfo.maxDiscountAmount) {
                        this.discount = this.policyInfo.maxDiscountAmount;
                    }
                    break;
                case 4:
                    let payment = decimal.sub(amount, this.noDiscountPrice);
                    let multiple = parseInt(decimal.div(payment, this.policyInfo.minSalesOrderAmountOfDiscount));
                    this.discount = decimal.mul(this.policyInfo.discountAmount, multiple);
                    break;
                default:
                    this.discount = 0;
                    break;
            }

            this.payNoDiscountPrice = this.noDiscountPrice

            //if((amount-this.discount - this.noDiscountPrice)>=this.voucher.paymentAmountThreshold){
            if ((decimal.sub(amount, this.discount)) >= this.voucher.paymentAmountThreshold) {
                this.voucherUse = this.voucher.deductionValue; //优惠券使用金额
                // return true; //
            }

        },
        isAllowPromotionVoucher() {
            //是否开启配置信息
            this.$http.post('/api/allowPromotionVoucher').then((res) => {
                if (res.body.code === '1000' && res.body.resData) {
                    this.getVoucher();
                }
            })
        },
        // 获取注册用户代金券
        getVoucher() {
            this.$http.post('/api/voucher').then(res => {
                const result = res.data
                this.isShow = res.body.isShow
                // this.isChance = res.body.isChance
                if (!result.mobile) {
                    this.$layer.dialog({
                        content: '该账号未绑定手机号，请去盖象商城绑定',
                        btn: ['知道了']
                    }).then(res => {
                        if (res === 0) {
                            this.$router.back()
                        }
                    })
                    return false
                }
                //检测是否开启H5开关
                //是否开启配置信息
                this.$http.post('/api/allowPromotionVoucher').then((res1) => {
                    if (res1.body.code === '1000' && res1.body.resData) { //判断是否开启
                        if (result.data.status == '1000') {
                            const voucher = result.data.voucher;
                            if (voucher.length > 0) {
                                voucher.forEach(element => {
                                    //未过期的拉新代金券
                                    let beginTime = new Date(element.validTime);
                                    // 非东八区的强制使用东八区，仅用于解决浏览器差异，不处理客户端时区差异
                                    let t2 = new Date(element.validTime + '+08:00')
                                    if (beginTime.getHours() !== t2.getHours()) {
                                        beginTime = t2
                                    }
                                    let endTime = new Date(element.useExpireTime);
                                    let t3 = new Date(element.useExpireTime + '+08:00')
                                    if (endTime.getHours() !== t3.getHours()) {
                                        endTime = t3
                                    }
                                    const d = new Date();
                                    if (beginTime <= d && endTime > d) {
                                        this.voucherValue += element.deductionValue;
                                        if (element.voucherType == 101) {
                                            this.voucher = element;
                                        }
                                    }

                                });
                            }
                            if (this.voucher.deductionValue) {
                                this.voucherValue = 0 //有拉新，则不提示
                            }
                        } else {
                            console.log('该账号无代金券')
                        }
                    }
                })
                if (this.isShow || this.fromPath === 'Register') {
                    //查询是否可以获得代金券
                    this.$http.post('/api/getUserVoucherByCode').then((rte) => {
                        //有绑定关系就弹出
                        this.mdShow = true;
                        let resultVoucher = rte.body
                        if (rte.body.code === '1000') {
                            if (resultVoucher.resData.isGetVouchers) {
                                this.isChance = false
                                this.vouchersAmount = resultVoucher.resData.vouchersAmount
                            } else {
                                this.isChance = true
                            }
                        }
                    })
                }
            }, res => {
                console.log('代金券接口异常稍后重试');
            })
        },
        closeModal() {
            this.mdShow = false;
        },
    }
}
</script>

<style scoped>
/*主体样式*/
.pay-list,
.discount,
.consumption {
  background: #fff;
  width: 95%;
  border: 1px solid #e9e9e9;
  margin: 0.2667rem auto;
}
.consumption > div {
  height: 1.6rem;
  line-height: 1.6rem;
  padding-left: 0.1333rem;
  border-bottom: 1px solid #e9e9e9;
}
.consumption > div input {
  height: 1.4rem;
}
.consumption > div:last-child,
#discount > div:last-child {
  border: 0;
}
.pay-list-title {
  width: 95%;
  margin: 0 auto;
}
.discount {
  color: #ff3e32;
  margin-top: 0.8rem;
}
.discount > div,
.pay-list > div {
  height: 1.2rem;
  line-height: 1.2rem;
  border-bottom: 1px solid #e9e9e9;
  padding: 0 0.2667rem;
}
.discount > div:last-child,
.pay-list > div:last-child {
  border: 0;
}
.discount > div p {
  float: right;
}
#payment.disabled {
  background: #939393;
}
#payment {
  display: block;
  width: 7.2rem;
  height: 1.1467rem;
  background: #53beb3;
  color: #fff;
  margin: 0.9333rem auto;
}
.mask {
  position: fixed;
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
  background: #000;
  opacity: 0.6;
  z-index: 10;
}
.modal {
  position: fixed;
  width: 6.9333rem;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  z-index: 88;
}
.messageBox {
  width: 100%;
  background: #fff;
  border-radius: 0.08rem;
  padding-top: 0.6667rem;
  text-align: center;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
  overflow: hidden;
}
.messageBox .success {
  width: 2.1333rem;
  height: 2.1333rem;
  border-radius: 50%;
  background: #09bebf;
  margin: 0 auto 0.5333rem;
  padding-top: 0.6533rem;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
}
.messageBox .success p {
  width: 1.2rem;
  height: 0.84rem;
  background: url('../assets/images/pay_success.png') no-repeat;
  background-size: 100%;
  margin: 0 auto;
}
.messageBox .amount {
  font-size: 0.48rem;
  color: #ff3b30;
}
.messageBox .message {
  color: #989999;
  font-size: 0.36rem;
  margin-top: 0.4rem;
  line-height: 0.6rem;
}
.modal .close {
  display: block;
  width: 2.4rem;
  height: 0.8rem;
  line-height: 0.8rem;
  border: 1px solid #797877;
  border-radius: 0.12rem;
  margin: 0.4rem auto;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
}
input::-webkit-input-placeholder {
  color: #999 !important;
}
input:-moz-placeholder {
  color: #999 !important;
}
input::-moz-placeholder {
  color: #999 !important;
}
input:-ms-input-placeholder {
  color: #999 !important;
}
</style>
